import { ColorUtilInstance, getThemeColor, setNavBgToStorage, updateNavigationBackgroundColors, clearThemeColor, getNavBgToStorage } from '@src/util/business/color';
import { getSettingInfoId } from '@src/api/CommonApi'

/**
 * @description 更新主题色和导航栏背景缓存数据，并且更新导航栏背景颜色
 * @param {*} themeColor 主题色颜色
 * @param {*} navBg 导航栏颜色
 */
function updateCacheThemeAndNavBg(themeColor, navBg) {
    if (themeColor) {
        ColorUtilInstance.setThemeColor(themeColor);
    }
    if (navBg) {
        // 将获取的导航栏背景存储到本地
        setNavBgToStorage(navBg);
        updateNavigationBackgroundColors(navBg);
    }
}


function updateThemeAndNavBg() {
    ColorUtilInstance.initThemeColor();
    setThemeToRootWindow()
    updateNavigationBackgroundColors(getNavBgToStorage());
}

/**
 * @description 设置主题色到根窗口
 */
function setThemeToRootWindow() {
    ColorUtilInstance.setThemeToRootWindow(getThemeColor());
}


/**
 * @description 更新主题色
 * @param {*} data 数据
 */
export async function updateThemeColor(data) {
    try {
        const res = await getSettingInfoId(data?.user?.tenantId);
        if (!res.data || !res.data.settingPageParam) {
            // 当不存在主题色时清空主题色缓存
            clearThemeColor();
        } else {
            const { systemThemeBackgroundColor, navigationBackgroundColor } = res.data.settingPageParam.globalSettingParam;
            updateCacheThemeAndNavBg(systemThemeBackgroundColor, navigationBackgroundColor)
        }
    } catch (error) {
        console.log(error)
    }
    updateThemeAndNavBg()
}